<?php

namespace app\admin\controller\school;

use app\common\controller\Backend;
use app\common\library\Hypy;
use fast\Random;
use fast\Tree;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;

/**
 * 
 *
 * @icon fa fa-file
 */
class School extends Backend
{
    
    /**
     * School模型对象
     */
    protected $model = null;
    protected $noNeedRight=["lists","lists2","status"];
    protected $noNeedLogin=["lists","lists2","status"];
//    protected $multiFields='is_official';


    public function _initialize()
    {
        parent::_initialize();
        $this->shopid=false;
        $this->model = model('School');
        $this->modelValidate = true;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        // 添加session检查
        if (!isset($_SESSION['think']['admin']) || !isset($_SESSION['think']['admin']['group_id'])) {
            session_destroy();
            $this->redirect('/index/logout');
            return;
        }
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 获取城市和学校过滤参数
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");
            
            // 调试日志
            error_log("School Index - city_id: $city_id, school_id: $school_id");

            $total = $this->model
                ->where($where);

            $total = $total->where("status", "<>", -1);
            
            // 添加城市过滤
            if (!empty($city_id)) {
                $total = $total->where("city_id", "=", $city_id);
            } else if ($_SESSION['think']['admin']['group_id'] == 2) {
                $total = $total->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }
            
            // 添加学校过滤
            if (!empty($school_id)) {
                $total = $total->where("id", "=", $school_id);
            }
            
            $total = $total
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where);
                
            // 添加城市过滤
            if (!empty($city_id)) {
                $list = $list->where("city_id", "=", $city_id);
            } else if ($_SESSION['think']['admin']['group_id'] == 2) {
                $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }
            
            // 添加学校过滤
            if (!empty($school_id)) {
                $list = $list->where("id", "=", $school_id);
            }
            
            $list = $list->where("status", "<>", -1);
            $list = $list->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $this->model->getLastSql();

            $list = collection($list)->toArray();
            for($i=0;$i<count($list);$i++){
               $list[$i]['district_id']=$this->model->getDistrict_idTextAttr($list[$i]['district_id'],$list[$i]);
                $list[$i]['city_id']=$this->model->getCity_idTextAttr($list[$i]['city_id'],$list[$i]);

            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assign('user_type', $_SESSION['think']['admin']['group_id']);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['create_time']=$datatime;
                    unset($params['delete_time']);
                    unset($params['update_time']);
                    if($_SESSION['think']['admin']['group_id']==2){
                        $params['city_id']=$_SESSION['think']['admin']['city_id'];
                        //如果是城市用户开通了学校
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $r=$this->model->where("name","=",$params['name'])->where("create_time","=",$params['create_time'])->select();
                    if($result){
                        //新建这个学校管理员帐号
                        $data=array();
                        $data['salt'] = Random::alnum();
                        $orgusername=$data['username'] = Hypy::shouzhimu($params["name"])."cqadmin";
                        $index=1;
                        while(model("Admin")->where("username","=", $data['username'])->find()){
                            $data['username']= $orgusername.$index++;
                        }
                        $data['nickname']= $params["name"]."城区管理员";
                        $data['password'] = $this->auth->getEncryptPassword("159456", $data['salt']);
                        $data['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                        $data['province_id'] = $params["province_id"];
                        $data['city_id'] = $params["city_id"];
                        $data['district_id'] = $params["district_id"];
                        $data['school_id'] = $r[0]["id"];
                        $data['community_id'] = 0;
                        $result = model("Admin")->allowField(true)->save($data);

                        // 获取刚创建的管理员ID
                        $admin = model("Admin")->where("username", "=", $data['username'])->find();
                        if ($admin) {
                            // 为管理员分配用户组
                            $groupData = array();
                            $groupData['uid'] = $admin['id'];
                            $groupData['group_id'] = 3; // 学校管理员组
                            $result = model("AuthGroupAccess")->allowField(true)->save($groupData);
                        }
                    }
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign('user_type', $_SESSION['think']['admin']['group_id']);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        if($ids==null){
            $ids=$_SESSION['think']['admin']['school_id'];
        }
        $row = $this->model->get($ids);
        if (!$row)
        $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['update_time']=$datatime;
                    unset($params['delete_time']);
                    unset($params['create_time']);
                    if(isset($params['is_official'])&&$params['is_official']==1){
                        $params['is_official']=1;
                    }else{
                        $params['is_official']=0;
                    }
                    $result = $row->allowField(true)->validate('School.edit')->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();

    }


    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row=$this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL){
        $where="";
        $page=1;
        $pagesize=50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                $where = "where 1=0";
                if (isset($_REQUEST['cityId'])&&$_REQUEST['cityId'] > 0) {
                    $where .= " and city_id=" . $_REQUEST['cityId'];
                }
                if (isset($_REQUEST['districtId'])&&$_REQUEST['districtId'] > 0) {
                    $where .= " and district_id=" . $_REQUEST['districtId'];
                }
                $where .= " and (1=0 ";
                if ($keyValue != "") {
                    $nn = preg_split("/\,/", $keyValue);
                    for ($i = 0; $i < count($nn); $i++) {
                        $where .= " or $keyField='{$nn[$i]}'";
                    }
                }
                $where .= ")";
            }else{
                $where="where status=1";
                if(isset($_REQUEST['cityId'])&&$_REQUEST['cityId']>0){
                    $where.=" and city_id=".$_REQUEST['cityId'];
                }
                if(isset($_REQUEST['districtId'])&&$_REQUEST['districtId']>0){
                    $where.=" and district_id=".$_REQUEST['districtId'];
                }
            }
        }
        $sql="select id,name name from dev002_gxyusheng.eb_school $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        //echo $sql;
        $list = db()->query($sql);

        //$tree = Tree::instance();
        //$tree->init($list, 'pid');
        //if(isset($keyValue)&&$keyValue!=""){
        //}else{
        //    $list=$tree->getTreeList($tree->getTreeArray(0), 'name');
        //    //array_unshift($list,array("name"=>"无父级","pid"=>0,"weigh"=>9999));
        //}

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.eb_school $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    public function lists2($ids = NULL){
        $where="";
        $page=1;
        $pagesize=50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                $where = "where 1=0";
                if (isset($_REQUEST['cityId'])&&$_REQUEST['cityId'] > 0) {
                    $where .= " and city_id=" . $_REQUEST['cityId'];
                }
                if (isset($_REQUEST['districtId'])&&$_REQUEST['districtId'] > 0) {
                    $where .= " and district_id=" . $_REQUEST['districtId'];
                }
                $where .= " and (1=0 ";
                if ($keyValue != "") {
                    $nn = preg_split("/\,/", $keyValue);
                    for ($i = 0; $i < count($nn); $i++) {
                        $where .= " or $keyField='{$nn[$i]}'";
                    }
                }
                $where .= ")";
            }else{
                $where="where 1=1";
                if($_SESSION['think']['admin']['group_id']==8){
                    if(isset($_REQUEST['cityId'])&&$_REQUEST['cityId']>0){
                        $where.=" and city_id=".$_REQUEST['cityId'];
                    }
                    if(isset($_REQUEST['districtId'])&&$_REQUEST['districtId']>0){
                        $where.=" and district_id=".$_REQUEST['districtId'];
                    }
                }
            }
        }
        $where.=" and level<=1";
        $sql="select id,pid,name name from dev002_gxyusheng.fa_subject_lv $where ";
        $list = db()->query($sql);

        $tree = Tree::instance();
        $tree->init($list, 'pid');
        if(isset($keyValue)&&$keyValue!=""){
        }else{
            $list=$tree->getTreeList($tree->getTreeArray(0), 'name');
            //array_unshift($list,array("name"=>"无父级","pid"=>0,"weigh"=>9999));
        }

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.fa_subject_lv $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }


    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }


    public function is_official($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("is_official")->find();
            $v=$result->is_official==1?0:1;
            $this->model->where("id","=",$ids)->update(["is_official"=>$v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }
    

    public function is_collected($school_id){
        $user=$this->auth->getUser(true);
        if(!$user){
            return false;
        }
        $user_id=$user['uid'];
        try{
            $result=Db::name('user_collect')->where(['uid'=>$user_id,'type'=>3,'rel_id'=>$school_id])->find();
            if($result){
                return true;
            }else{
                return false;
            }
        }catch(Exception $e){
            $this->error('切换失败!'.$e->getMessage());
        }
    }
}
